<?php


namespace common\services;


use common\enumeration\PushMessageEnum;
use common\enumeration\RedisKeyEnum;
use common\exception\ErrorException;
use common\helpers\Util;
use common\models\PushMessage;
use common\models\PushMessageLog;
use common\models\User;
use JPush\Client as JPush;
use yii\redis\Connection;

class PushService
{

    const RADIO_PUSH_PHONE_RECHARGE = 1;
    const RADIO_PUSH_REDEEM = 2;
    const RADIO_PUSH_TRANS_BUY = 3;
    const RADIO_PUSH_TRANS_SALE = 4;

    //跑马灯推送类型
    const RADIO_PUSH_TYPE = [
        self::RADIO_PUSH_PHONE_RECHARGE => '话费充值推送',
        self::RADIO_PUSH_REDEEM => '提现成功推送',
        self::RADIO_PUSH_TRANS_BUY => '交易所购买成功推送',
        self::RADIO_PUSH_TRANS_SALE => '交易所卖出成功推送',
    ];

    /**
     * 单用户及时推送，多用户请通过队列推送
     * @param PushMessage $pushMessage
     * @return bool
     * @throws ErrorException
     */
    public static function pushToUser(PushMessage $pushMessage)
    {
        $user_id = trim($pushMessage->user_ids, ',');
        if (count(explode(',', $user_id)) > 1) {
            throw new ErrorException("推送用户过多");
        }
        $user = User::findOne($user_id);
        if (!empty($user)) {
            if (empty($user['device'])) {
                PushMessage::updateAll(['status' => PushMessage::STATUS_RUN_SUCCESS], ['id' => $pushMessage->id]);
                return true;
            }

            $conf = PushMessageEnum::PUSH_CONF[PushMessageEnum::PUSH_SOURCE0];
            if (in_array($user['login_source'], PushMessageEnum::PUSH_OTHER_KEYS)) {
                $conf = PushMessageEnum::PUSH_CONF[$user['login_source']];
            }

            $extras = [
                'message_id' => $pushMessage->id,
                'title' => $pushMessage->title,
                'content' => $pushMessage->content,
                'type' => $pushMessage->open_type,
                'data' => empty($pushMessage->open_type_args) ? "" : $pushMessage->open_type_args
            ];

            try {
                $client = new JPush($conf['key'], $conf['secret'], null);
                $response = $client->push()
                    ->setPlatform(['ios', 'android'])
                    ->addRegistrationId([$user['device']])
                    ->message($extras['content'], [
                        'extras' => $extras
                    ])->send();
                $logMessage = json_encode($response);
                PushMessage::updateAll(['status' => PushMessage::STATUS_RUN_SUCCESS], ['id' => $pushMessage->id]);
            } catch (\Exception $exception) {
                PushMessage::updateAll(['status' => PushMessage::STATUS_RUN_ERROR], ['id' => $pushMessage->id]);
                $logMessage = Util::exceptionToString($exception);
                \Yii::error("推送错误" . $logMessage);
            }
            self::addPushMessageLog($pushMessage->id, $pushMessage->user_ids, $logMessage, $user['login_source']);
        }
        return true;
    }

    /**
     * 增加推送日志
     * @param $message_id
     * @param $users
     * @param $response
     * @param $source
     * @return bool
     */
    private static function addPushMessageLog($message_id, $users, $response, $source)
    {
        $pushMessageLog = new PushMessageLog([
            'push_message_id' => $message_id,
            'users' => $users,
            'response' => $response,
            'source' => $source,
            'create_time' => date("Y-m-d H:i:s")
        ]);
        return $pushMessageLog->save(false);
    }
    

}